﻿using System.Collections.Generic;
using System.Threading.Tasks;
using GrapeCity.Forguncy.Commands;
using TencentCloud.Common;
using TencentCloud.Ocr.V20181119.Models;
using TencentCloudOcrPlugin.Resources;

namespace TencentCloudOcrPlugin.Ocr
{
    public class OcrPassportAction : OcrActionBase
    {
        private static readonly Dictionary<string, string> ParamsDict = new Dictionary<string, string>();

        public OcrPassportAction()
        {
            ParamsDict["Country"] = "国家码";
            ParamsDict["PassportNo"] = "护照号";
            ParamsDict["Sex"] = "性别";
            ParamsDict["Nationality"] = "国籍";
            ParamsDict["BirthDate"] = "出生日期";
            ParamsDict["BirthPlace"] = "出生地点";
            ParamsDict["IssueDate"] = "签发日期";
            ParamsDict["IssuePlace"] = "签发地点";
            ParamsDict["ExpiryDate"] = "有效期";
            ParamsDict["Signature"] = "持证人签名";
            ParamsDict["CodeSet"] = "最下方第一行MRZCode序列";
            ParamsDict["CodeCrc"] = "最下方第二行MRZCode序列";
            ParamsDict["Name"] = "姓名";
            ParamsDict["FamilyName"] = "姓";
            ParamsDict["FirstName"] = "名";
        }
        
        public override List<string> GetParamList(TencentCloudApiPropertyBase properties)
        {
            var list = base.GetParamList(properties);
            list.AddRange(ParamsDict.Values);
            return list;
        }

        public override async Task<Dictionary<string,object>> RunAsync(TencentCloudApiClientConfig clientConfig,
            IServerCommandExecuteContext dataContext, TencentCloudApiPropertyBase properties)
        {
            var businessCardProperties = properties as OcrPassportProperties;
            var baseRequest = await BuildRequestAsync(businessCardProperties, dataContext);
            var request = new PassportOCRRequest()
            {
                ImageBase64 = baseRequest.ImageBase64,
                ImageUrl = baseRequest.ImageUrl
            };
            var response = await GetClient(clientConfig).PassportOCR(request);
            return BuildResp(response, properties);
        }

        private Dictionary<string, object> BuildResp(AbstractModel tencentResp, TencentCloudApiPropertyBase properties) {
            var dict = new Dictionary<string, object>();
            if (!(tencentResp is PassportOCRResponse response))
            {
                return dict;
            }
            if (properties.advancedSettings.TencentRawResp)
            {
                dict["原始数据"] = tencentResp;
            }
            var type = typeof(PassportOCRResponse);
            foreach (var keyValuePair in ParamsDict)
            {
                dict[ParamsDict[keyValuePair.Key]]  = type.GetProperty(keyValuePair.Key)?.GetValue(response);
            }            
            return dict;
        }
    }
}